package com.zidian.teacher.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.teacher.R;
import com.zidian.teacher.adapter.EvaluateCustomAdapter;
import com.zidian.teacher.bean.EvaluateCustomBean;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by GongCheng on 2017/1/9.
 */

public class CustomEvaFragment extends Fragment {
    @Bind(R.id.list)
    RecyclerView customRecyclerView;
    @Bind(R.id.swipe_refresh_widget)
    SwipeRefreshLayout swipeRefreshWidget;

    private EvaluateCustomAdapter adapter;
    private Handler handler = new Handler();
    private EvaluateCustomBean.DataBean bean;
    private List<EvaluateCustomBean.DataBean.ListBean> customData = new ArrayList<>();
    private int start_row = 1;
    private boolean isLoading;
    //RecycleView是否正在刷新
    private boolean isRefreshing = false;

    public static CustomEvaFragment newInstance() {

        Bundle args = new Bundle();
        CustomEvaFragment fragment = new CustomEvaFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_evaluate_detail_custom, container, false);
        ButterKnife.bind(this, view);
        initView();
        initData();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void initView() {

        adapter = new EvaluateCustomAdapter(getActivity(), customData, bean);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        customRecyclerView.setLayoutManager(layoutManager);
        customRecyclerView.setAdapter(adapter);
        swipeRefreshWidget.setColorSchemeResources(R.color.colorAccent);
        swipeRefreshWidget.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshWidget.setRefreshing(true);
                isRefreshing = true;
            }
        });
        swipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        customData.clear();
                        start_row = 1;
                        isRefreshing = true;
                        getCourse(start_row + "");
                    }
                }, 2000);
            }
        });
        customRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isRefreshing) {
                    return true;
                } else{
                    return false;
                }
            }
        });

        customRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = swipeRefreshWidget.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                start_row++;
                                getCourse(start_row + "");
                                Log.d("test", "load more completed");
                                isLoading = false;
                            }
                        }, 1000);
                    }
                }
            }
        });

    }

    public void initData() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getCourse(start_row + "");
            }
        }, 1500);

    }
    private void getCourse(final String startrow) {
        String loginUrl = Constant.URL_TEACHER + "EvaluateTeacher/CustomEvaluation";
        HashMap<String, String> map = new HashMap<>();
        map.put("startrow", startrow);
        map.put("pageSize", "10");
        map.put("teacherId", GetUserInfo.getTeacherId(getActivity()));
        map.put("operatorType", "教师");
        map.put("operatorId", GetUserInfo.getTeacherId(getActivity()));
        map.put("token", GetUserInfo.getToken(getActivity()));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
                if (swipeRefreshWidget != null) {
                    swipeRefreshWidget.setRefreshing(false);
                }
                isRefreshing = false;
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("T", response);
                if (swipeRefreshWidget != null) {
                    swipeRefreshWidget.setRefreshing(false);
                }
                isRefreshing = false;
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        isLoading = true;
                        adapter.setHasMore(false);
                        adapter.notifyDataSetChanged();
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        ToastUtil.showToast(getActivity(), jsonObject.getString("message"));
                        return;
                    }

                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                EvaluateCustomBean model = gson.fromJson(response, EvaluateCustomBean.class);
                if (model.isSuccess()) {
                    if (model.getData().getList().size() < 10) {
                        isLoading = true;
                        adapter.setHasMore(false);
                    } else {
                        isLoading = false;
                        adapter.setHasMore(true);
                    }
                    if (startrow.equals("1")) {
                        customData.clear();;
                        customData.addAll(model.getData().getList());
                    } else {
                        customData.addAll(model.getData().getList());
                    }

                    bean = model.getData();
                    adapter.setEvaluateTeacher(bean);
                    adapter.notifyDataSetChanged();
                    adapter.notifyItemRemoved(adapter.getItemCount());
                }
            }
        });
    }
}
